#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "key_drv.h"
#include "systick.h"
#include "delay.h"
#include "lcd_drv.h"
#include "RTT_Debug.h"
#include "hmi_common.h"
#include "store_app.h"
#include "wifi_app.h"
#include "iap_drv.h"

extern AsciiFontDesc_t g_fontAscii10x20;

#define CURRENT_VER_POS_X        	50
#define CURRENT_VER_POS_Y       	150
#define NEW_VER_POS_X        	    50
#define NEW_VER_POS_Y       	    250

static uint8_t otaFlag = 0;

uint8_t GetOtaUpdateFlag(void)
{
    uint8_t index = otaFlag;
    otaFlag = 0;
    return index;
}

static void DisplayOtaInfo(void)
{
    char version[10] = {0};
	char strBuf[30] = {0};
	uint32_t binSize; 
	GetSoftwareVersionParam(version);   
	sprintf(strBuf, "Current ver: %s", version);
	LcdDrawString(CURRENT_VER_POS_X, CURRENT_VER_POS_Y, strBuf, BLUE, BLACK, &g_fontAscii10x20);
	memset(version, 0, sizeof(version));
	memset(strBuf, 0, sizeof(strBuf));
    if (GetWifiConnectStatus() == WIFI_CONNECT_SERVER_SUCESS)
    {
        if (!GetNewVersionInfo(version, &binSize))
        {
            LcdDrawString(10, 200, "Searching for update ..", BLUE, BLACK, &g_fontAscii10x20);
            return;
        }
        else
        {
            otaFlag = 1;
            sprintf(strBuf, "new ver: %s", version);
            LcdDrawString(NEW_VER_POS_X, NEW_VER_POS_Y, strBuf, RED, BLACK, &g_fontAscii10x20);
            memset(strBuf, 0, sizeof(strBuf));
            sprintf(strBuf, "bin size: %d", binSize);
            LcdDrawString(NEW_VER_POS_X , NEW_VER_POS_Y + 40, strBuf, RED, BLACK, &g_fontAscii10x20);
            LcdDrawString(0 , 200, "double pressed to update", RED, BLACK, &g_fontAscii10x20);
        }
    }
  	else
    {
        LcdDrawString(10, 200, "Please connect network .", BLUE, BLACK, &g_fontAscii10x20);
    }
}

void OtaUpdate(void)
{
    SetUpdateVerFlag();
		ResetToBoot();
}

void DisplayOtaUpdatePage(void)
{
    DisplayStatusBar();
    DisplayOtaInfo();
}
